package com.huxiaoshou.exam.config;

import com.huxiaoshou.exam.config.properties.ThreadProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadPoolConfig {

    @Autowired
    private ThreadProperties threadProperties;

    // 定义线程池Bean
    @Bean(destroyMethod = "shutdown")
    public ThreadPoolExecutor taskExecutor() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                threadProperties.getCorePoolSize(),
                threadProperties.getMaxPoolSize(),
                threadProperties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(threadProperties.getQueueCapacity()),
                new MyThreadFactory("task"),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );

        // 允许核心线程超时关闭，避免资源浪费
        executor.allowCoreThreadTimeOut(true);
        return executor;
    }

}